package com.trainsmart.example.demo.model
{
	import com.trainsmart.smartmvc.IModel;
	
	import flash.events.Event;
	
	import mx.rpc.events.FaultEvent;
	
	public class UserDAO implements  IModel
	{
		/**
		 * just use static variable to storage vo.
		 * This class will be replaced by Database or RemoteObject, WebService, HttpService, even XML		
		 */ 
		private static var cache:Array = new Array();
		
		private var _VO:Class = null;
		public function UserDAO(VO:Class)
		{
			_VO = VO;
		}
		
		public function save(vo:*, response:Function=null, resultHandler:Event=null, faultHandler:FaultEvent=null):void{
			var uservo:UserVO=getVO(vo);
			cache[uservo.userId.toString()] = uservo;
			if(response!=null) 
			   response();
		}
		public function remove(vo:*, response:Function=null,  resultHandler:Event=null, faultHandler:FaultEvent=null):void{
			var uservo:UserVO=getVO(vo);
			cache[uservo.userId.toString()]  = null;
			if(response!=null) 
			   response();
		}
		public function update(vo:*, response:Function=null,  resultHandler:Event=null, faultHandler:FaultEvent=null):void{
			var uservo:UserVO=getVO(vo);
			cache[uservo.userId.toString()]  = uservo;
			if(response!=null) 
			   response();
		}
		
		public function findById(userId:*, response:Function=null,  resultHandler:Event=null, faultHandler:FaultEvent=null):void{
			var vo:UserVO =  cache[userId.toString()] as UserVO;
			if(response!=null)
				response(vo);
		}
		
		public 	function findByProperties(args:Array, response:Function=null, resultHandler:Event=null, faultHandler:FaultEvent=null):void{
			var users:Array = new Array();
			for each (var u:UserVO in cache){				
				users.push(u);
			}
			response(users);
		}
		
		public function checkVO(vo:*):void{
			if(!(vo is _VO)) throw new Error("vo is not compatible");	
		}
		private function getVO(vo:*):UserVO{
			checkVO(vo);
			return vo as UserVO;
		}

	}
}